using MediatR;
using Traceability.API.APPLications.Commands.TraceabilityInfo;
using Traceability.API.Dtos;
using Traceability.API.Services;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.TraceabilityInfoshow
{
    public class AddTraceabilityInfoCommandHandler : IRequestHandler<AddTraceabilityInfoCommand, APIResult<int>>
    {
        private readonly IBaseRepository<TraceabilityInfo> _repository;
        private readonly TraceabilityRedisHelper _redisHelper;
        
        public AddTraceabilityInfoCommandHandler(
            IBaseRepository<TraceabilityInfo> repository,
            TraceabilityRedisHelper redisHelper)
        {
            _repository = repository;
            _redisHelper = redisHelper;
        }

        public async Task<APIResult<int>> Handle(AddTraceabilityInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            
            try
            {
                var traceabilityInfo = new TraceabilityInfo
                {
                    ProductId = request.ProductId,
                    ProductionBatch = request.ProductionBatch,
                    ShelfLife = request.ShelfLife,
                    ProductionLicenseNumber = request.ProductionLicenseNumber,
                    ManufacturerName = request.ManufacturerName,
                    InformationCompleteness = request.InformationCompleteness,
                    PhotoUrl = request.PhotoUrl,
                    CreatedBy = request.CreatedBy,
                    CreatedTime = DateTime.Now
                };
                
                result.Data = await _repository.Add(traceabilityInfo);
                
                // 添加成功后，缓存到Redis
                if (result.Data > 0)
                {
                    await _redisHelper.CacheTraceabilityInfoAsync(traceabilityInfo);
                    
                    // 清除列表缓存，以便下次获取最新数据
                    await _redisHelper.RemoveTraceabilityListAsync();
                }
                
                result.Code = APIEnum.添加成功;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.添加失败;
                result.Message = ex.Message;
            }
            
            return result;
        }
    }
}